﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BigLotterySyndicate.Classes;
using SyndicateDAO.DatabaseObject;
using SyndicateBusiness.Classes;
using System.IO;
using System.Net;

namespace BigLotterySyndicate.MyAccount
{
    public partial class Default : BasePlayerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Visible)
                return;

            if (!IsUserLoggedIn)
                return;

            this.MasterPagePlayer.SetTopMenuTab(global::BigLotterySyndicate.MyAccount.Controls.TopNav.AdminNavSection.Home);
       
            this.PageTitle += " My draws";

            SetList();

            if (!Page.IsPostBack)
            {
                CheckToken();                
            }
            
        }
        #region token

        static public byte[] GetBytesFromUrl(string url)
        {
            byte[] b;
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            WebResponse myResp = myReq.GetResponse();

            Stream stream = myResp.GetResponseStream();
            //int i;
            using (BinaryReader br = new BinaryReader(stream))
            {
                //i = (int)(stream.Length);
                b = br.ReadBytes(500000);
                br.Close();
            }
            myResp.Close();
            return b;
        }


        static public void WriteBytesToFile(string fileName, byte[] content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);
            try
            {
                w.Write(content);
            }
            finally
            {
                fs.Close();
                w.Close();
            }

        }


        #endregion

        private void CheckToken()
        {
            string token = this.LoggedInUser.xmlToken;

            string imagePath = "/Tokens/"+token+".jpg";

            if(!File.Exists(Server.MapPath(imagePath)))
            {
                string url =String.Format("http://qrcode.kaywa.com/img.php?s=5&d={0}",token);

                var content = GetBytesFromUrl(url);

                string newFile = token+".jpg";

                WriteBytesToFile(Server.MapPath("/Content/Tokens/"+newFile), content);
            }

            this.imgTokenImage.ImageUrl = PrintMyTokenPath();

            this.imgTokenImage.ToolTip += ":" + token;

        }

        private void SetList()
        {
            litManagers.Text = String.Join(", ", this.BusinessFacade.UserBL.GetAllBySyndicateId(this.LoggedInUser.syndicateId).Where(u => u.isAdmin).Select(u => u.username).OrderBy(u => u).ToArray());
        

            if (Page.IsPostBack)
                return;

            BindList();
            
            }

        private void BindList()
        {
            var query = this.BusinessFacade.PlayerBL.GetDrawsByPlayerId(LoggedInUser.id).OrderByDescending(d => d.drawdate);

            this.TopPager.RecordCount = this.BottomPager.RecordCount = query.Count() ;

            if (this.TopPager.RecordCount > 0)
            {
                this.RepeaterList.DataSource = query.Skip(this.TopPager.StartIndex - 1).Take(this.TopPager.PageSize);
                this.RepeaterList.ItemDataBound += new RepeaterItemEventHandler(RepeaterList_ItemDataBound);
                this.RepeaterList.DataBind();

                this.MultiViewList.SetActiveView(this.ViewList);
            }
            else
            {
                this.MultiViewList.SetActiveView(this.ViewEmpty);
            }
        }

        void RepeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            draw u = e.Item.DataItem as draw;

            BigLotterySyndicate.Secured.Controls.DrawListItem listItem = Utilities.FindControlRecursive(e.Item, "DrawListItem") as BigLotterySyndicate.Secured.Controls.DrawListItem;
            if (listItem != null)
                listItem.Draw = u;
        }

        protected void Pager_PageIndexChanged(object sender, global::BigLotterySyndicate.Controls.PageIndexChangedEvetArgs e)
        {
            this.TopPager.PageIndex = this.BottomPager.PageIndex = e.PageIndex;

            this.BindList();
        }

        protected string PrintFunds()
        {
            return String.Format("&pound;{0:0.00}", this.LoggedInUser.funds);
        }

        protected string PrintMoneySpend()
        {
            var draws = this.BusinessFacade.PlayerBL.GetDrawsByPlayerId(LoggedInUser.id);

            var fundsUsed = 0;

            foreach (var draw in draws)
            {
                if (!draw.freeDraw)
                {
                    if ((int)draw.pricePerLine == 0)
                    {
                        switch (draw.type)
                        {
                            case draw.drawType.EUROMILLIONS:
                                fundsUsed += 2;
                                break;
                            default:
                                fundsUsed += 1;
                                break;
                        }
                    }
                    else
                    {
                        fundsUsed += (int)draw.pricePerLine;
                    }
                }
            }


            return String.Format("&pound;{0:0.00}", fundsUsed);
        }

        protected string PrintMyTokenPath()
        {
            return String.Format("/Content/Tokens/{0}.jpg", this.LoggedInUser.xmlToken);
        }

        protected string PrintMyToken()
        {
            return this.LoggedInUser.xmlToken;
        }

        protected void ButtonRegenerate_Click(object sender, EventArgs e)
        {
            string currentToken = LoggedInUser.xmlToken;

            string oldPath = "/Content/Tokens/" + currentToken + ".jpg";

            string newToken = System.Guid.NewGuid().ToString();

            user u = this.BusinessFacade.UserBL.GetSingleUser(LoggedInUser.id);

            u.xmlToken = newToken;

            this.BusinessFacade.UserBL.UpdateUser();
            
            CheckToken();

            if (File.Exists(Server.MapPath(oldPath)))
            {
                File.Delete(Server.MapPath(oldPath));
            }

            Redirect("/MyAccount/Default.aspx?Ns=0");
        }

    }
}